<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
  import echarts from 'echarts'

  require('echarts/theme/macarons') // echarts theme
  import { debounce } from '@/utils'

  export default {
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '350px'
      },
      chartData: {
        type: Object,
        default: function() {
          return {
            'empCount': 5,
            'induction': 1,
            'departure': 1,
            'transfer': 1,
            'totalInvoice': 23,
            'billCount': 10,
            'costCount': 22,
            'projectCount': 1,
            'tenCount': 2,
            'isProCount': 1
          }
        }
      }
    },
    data() {
      return {
        chart: null
      }
    },
    mounted() {
      this.__resizeHanlder = debounce(() => {
        if (this.chart) {
          this.chart.resize()
        }
      }, 100)
      window.addEventListener('resize', this.__resizeHanlder)
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      window.removeEventListener('resize', this.__resizeHanlder)
      this.chart.dispose()
      this.chart = null
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$el, 'macarons')

        this.chart.setOption({
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          legend: {
            left: 'center',
            bottom: '10',
            data: ['投标项目', '中标项目', '立项项目']
          },
          color: ['#fbbbb3', '#9099cb', '#72beec', '#f9cb90'],
          calculable: true,
          series: [
            {
              name: '项目',
              type: 'pie',
              roseType: 'radius',
              radius: [15, 95],
              center: ['50%', '38%'],
              data: [
                { value: this.chartData.tenCount, name: '投标项目' },
                { value: this.chartData.isProCount, name: '中标项目' },
                { value: this.chartData.projectCount, name: '立项项目' }
              ],
              animationEasing: 'cubicInOut',
              animationDuration: 2600
            }
          ]
        })
      }
    },
    watch: {
      chartData() {
        this.initChart()
        this.chart.resize()
      }
    }
  }
</script>
